package com.java.basis.thread.n3;

import lombok.extern.slf4j.Slf4j;

/**
 * 两阶段终止模式
 *
 * @author wangning
 * @create 2022-01-17 20:23
 */
@Slf4j(topic = "c.Test03")
public class Test03 {
	public static void main(String[] args) throws InterruptedException {
		TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
		twoPhaseTermination.start();
		log.debug("开启监控");
		Thread.sleep(3500);
		twoPhaseTermination.stop();

	}

}

@Slf4j(topic = "c.TwoPhaseTermination")
class TwoPhaseTermination {
	private Thread monitor;
	//启动监控线程
	public void start() {
		monitor = new Thread(() -> {
			while (true) {
				Thread current = Thread.currentThread();
				if(current.isInterrupted()) {
					log.debug("料理后事");
					break;
				}
				try {
					Thread.sleep(1000);//情况1，此处两种情况下都有可能被打断，但是打断的情况不一样
					log.debug("执行监控记录");//情况2
				} catch (InterruptedException e) {
					e.printStackTrace();
					//重新设置打断标记为真
					current.interrupt();

				}

			}
		});
		monitor.start();
	}
	//停止监控线程
	public void stop() {
		monitor.interrupt();
	}


}
